package cn.itcast.activiti.servlet.processinstance;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.GraphicInfo;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;

import cn.itcast.activiti.common.ProcessEngineUtils;

/**
 * 查看流程图
 * @author Administrator
 *
 */
@WebServlet("/seeProcessDiagram.action")
public class SeeProcessDiagramServlet extends HttpServlet{

	private static final long serialVersionUID = 7378345467256193602L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//接收流程实例Id
		String piId=request.getParameter("piId");
		
		//获取流程擎
		ProcessEngine processEngine=ProcessEngineUtils.getProcessEngine();
		//获取运行时服务
		RuntimeService runtimeService=processEngine.getRuntimeService();
		//获取仓储服务
		RepositoryService repositoryService=processEngine.getRepositoryService();
		//  1. 通过流程实例ID获取流程定义ID(RuntimeService)
		ProcessInstance processInstance=runtimeService.createProcessInstanceQuery().processInstanceId(piId).singleResult();
		//2. 通过流程定义ID获取流程图(RepositoryService).
		InputStream inputStream=repositoryService.getProcessDiagram(processInstance.getProcessDefinitionId());
		/** 把流程图输入流转换成缓冲流图片 */
		BufferedImage image=ImageIO.read(inputStream);
		/** 获取画笔*/
		Graphics2D g=(Graphics2D) image.getGraphics();
		/** 设置画笔颜色 */
		g.setColor(Color.RED);
		/** 设置画笔粗细 */
		g.setStroke(new BasicStroke(3.0f));
		/** 消除锯齿 */
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		
		// 3. 获取流程定义文件中所有的节点的坐标信息(RepositoryService).
		BpmnModel bpmnModel =repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
		 //4. 获取当前活动的所有的节点ID(RuntimeService).
		List<String> activityIds=runtimeService.getActiveActivityIds(piId);
		// 5. 根据当前活动的节点id获取自己节点坐标信息
		for (String activityId : activityIds) {
			/** 根据当前活动的节点id获取自己节点坐标信息 */
			GraphicInfo gi=	bpmnModel.getGraphicInfo(activityId);
			g.drawRoundRect((int)gi.getX(), (int)gi.getY(), (int)gi.getWidth(), (int)gi.getHeight(), 10, 10);
			
		}
		
		/** 告诉浏览器响应的内容类型为图片 */
		response.setContentType("image/png");	   
	    /** 输出 */
		ImageIO.write(image, "png", response.getOutputStream());

	   
	    
		
	}

}
